package lazy.tool;

import java.lang.reflect.Method;

public class TestTool {
	public static void testPerformance(boolean isIgnoreException, Object target, String methodName, Object... methodArgs) {
		Class<?>[] types = new Class[methodArgs.length];
		for(int i=0;i<types.length;i++)
			types[i] = methodArgs[i]==null?null:methodArgs[i].getClass();
		testPerformance(isIgnoreException, target, methodName, types, methodArgs);
	}
	public static void testPerformance(boolean isIgnoreException, Object target, String methodName, Class<?>[] methodArgTypes, Object[] methodArgs) {
		try {
			Class<?> c;
			if(target instanceof Class<?>) {
				c = (Class<?>)target;
			} else {
				c = target.getClass();
			}
			testPerformance(10, 100000, isIgnoreException, target, c.getMethod(methodName, methodArgTypes), methodArgs);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("沒有此方法，無法測試！");
		}
	}
	public static void testPerformance(int testTimes, int loopTimes, boolean isIgnoreException, Object target, Method targetMethod, Object... methodArgs) {
		System.out.print("測試");
		System.out.print(targetMethod.getName());
		System.out.println("方法......");
		System.out.print("總共執行");
		System.out.print(testTimes);
		System.out.print("次，");
		System.out.print("每次執行");
		System.out.print(loopTimes);
		System.out.println("迴圈：");
		long totalMs = 0;
		long ms;
		for(int test=0;test<testTimes;test++) {
			ms = System.currentTimeMillis();
			for(int loop=0;loop<loopTimes;loop++) {
				try {
					targetMethod.invoke(target, methodArgs);
				} catch (Exception e) {
					if(!isIgnoreException) {
						e.printStackTrace();
						System.out.println("測試失敗！");
						return;
					}
				}
			}
			ms = System.currentTimeMillis()-ms;
			totalMs += ms;
			System.out.print("\t執行第");
			System.out.print(test+1);
			System.out.print("次：");
			System.out.print(ms);
			System.out.println("ms");
		}
		System.out.print("平均每次執行");
		System.out.print(totalMs/testTimes);
		System.out.println("ms");
	}
}
